package com.ate.aoligei.db;

import android.content.Context;
import android.util.Log;

import com.ate.green.db.DaoMaster;
import com.ate.green.db.DaoSession;

/**
 * @author Ate
 * @description:
 * @date :2020/11/11 19:40
 */
public class DbManager {
    private static final String DATABASE_NAME = "student_data";
    private static DbManager instance;

    private DaoSession daoSession;
    private DaoMaster.DevOpenHelper devOpenHelper;
    private DaoMaster daoMaster;

    public static DbManager getInstance() {
        if (instance == null) {
            synchronized (DbManager.class) {
                if (instance == null) {
                    instance = new DbManager();
                }
            }
        }
        return instance;
    }

    public DaoSession getDaoSession() {
        return daoSession;
    }

    //数据库初始化
    public void initDb(Context context) {
        devOpenHelper = new MySQLiteOpenHelper(context, DATABASE_NAME, null);
        daoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
        daoSession = daoMaster.newSession();
        Log.e("打开了数据库", devOpenHelper.getDatabaseName());
    }

    //关闭数据库
    public void closeDataBase() {
        if (devOpenHelper != null) {
            Log.e("关闭了数据库", devOpenHelper.getDatabaseName());
        }
        closeDaoSession();
        closeHelper();
    }

    private void closeHelper() {
        if (devOpenHelper != null) {
            daoSession.clear();
            daoSession = null;
        }
    }

    private void closeDaoSession() {
        if (devOpenHelper != null) {
            devOpenHelper.close();
            devOpenHelper = null;
        }
    }

}